<template>
  <div id="userManagePage">
    <!-- 星空背景 - 仅在此页面显示 -->
    <div class="starry-sky-container">
      <div class="stars stars-1"></div>
      <div class="stars stars-2"></div>
      <div class="stars stars-3"></div>
    </div>

    <!-- 搜索表单 -->
    <a-card class="search-card">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="账号">
          <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
        </a-form-item>
        <a-form-item label="用户名">
          <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="doTableChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'name'">
            <span>
              <smile-outlined />
              Name
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'userAvatar'">
            <a-image
              :src="record.userAvatar"
              :width="60"
              :height="60"
              class="user-avatar"
            />
          </template>
          <template v-else-if="column.dataIndex === 'userRole'">
            <div v-if="record.userRole === 'admin'">
              <a-tag color="green">管理员</a-tag>
            </div>
            <div v-else>
              <a-tag color="blue">普通用户</a-tag>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="openEditModal(record)">编辑</a-button>
              <a-button danger size="small" @click="doDelete(record.id)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑用户模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑用户"
      @ok="handleEditOk"
      @cancel="handleEditCancel"
      :confirm-loading="editConfirmLoading"
      :width="600"
    >
      <a-form layout="vertical" :model="editForm" class="edit-form">
        <a-form-item label="用户ID">
          <a-input v-model:value="editForm.id" disabled />
        </a-form-item>
        <a-form-item label="用户名" required>
          <a-input v-model:value="editForm.userName" />
        </a-form-item>
        <a-form-item label="用户头像">
          <a-input v-model:value="editForm.userAvatar" placeholder="请输入头像URL" />
        </a-form-item>
        <a-form-item label="用户简介">
          <a-textarea v-model:value="editForm.userProfile" :rows="3" />
        </a-form-item>
        <a-form-item label="用户角色" required>
          <a-select v-model:value="editForm.userRole">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { SmileOutlined } from '@ant-design/icons-vue';
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUser, listUserVoByPage, updateUser } from '@/api/userController.ts'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    width: 150,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    width: 150,
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    width: 100,
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    width: 200,
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]

// 数据
const data = ref<API.UserVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 编辑模态框相关
const editModalVisible = ref(false)
const editConfirmLoading = ref(false)
const editForm = reactive<API.UserUpdateRequest>({
  id: undefined,
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user'
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPage({
    ...searchParams,
  })
  if (res.data.data) {
    data.value = res.data.data.records ?? []
    total.value = res.data.data.totalRow ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 删除数据
const doDelete = async (id: any) => {
  if (!id) {
    return
  }

  // 确认删除
  const confirmed = await new Promise((resolve) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => resolve(true),
      onCancel: () => resolve(false),
    });
  });

  if (!confirmed) return;

  const res = await deleteUser({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

// 打开编辑模态框
const openEditModal = (record: API.UserVO) => {
  editForm.id = record.id
  editForm.userName = record.userName ?? ''
  editForm.userAvatar = record.userAvatar ?? ''
  editForm.userProfile = record.userProfile ?? ''
  editForm.userRole = record.userRole ?? 'user'
  editModalVisible.value = true
}

// 处理编辑确认
const handleEditOk = async () => {
  if (!editForm.userName) {
    message.error('用户名不能为空')
    return
  }

  if (!editForm.userRole) {
    message.error('用户角色不能为空')
    return
  }

  editConfirmLoading.value = true
  try {
    const res = await updateUser(editForm)
    if (res.data.code === 0) {
      message.success('更新成功')
      editModalVisible.value = false
      fetchData() // 刷新数据
    } else {
      message.error('更新失败，' + res.data.message)
    }
  } catch (error) {
    message.error('更新失败')
  } finally {
    editConfirmLoading.value = false
  }
}

// 处理编辑取消
const handleEditCancel = () => {
  editModalVisible.value = false
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 页面容器样式 */
#userManagePage {
  background-color: white;
  padding: 24px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

/* 表格卡片样式 */
.table-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  overflow: hidden;
}

.table-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

/* 自定义表格样式 */
:deep(.ant-table) {
  font-size: 14px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e8e8e8;
  padding: 16px;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f9fafb;
}

/* 用户头像样式 */
.user-avatar {
  border-radius: 50%;
  border: 2px solid #e6f7ff;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 按钮样式优化 */
:deep(.ant-btn-primary) {
  background-color: #1658d6;
  border-color: #7792d5;
  transition: all 0.3s ease;
}

:deep(.ant-btn-primary:hover) {
  background-color: #001da1;
  border-color: #133a80;
}

:deep(.ant-btn-danger) {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  transition: all 0.3s ease;
}

:deep(.ant-btn-danger:hover) {
  background-color: #ff7875;
  border-color: #ff7875;
}

/* 输入框样式 */
:deep(.ant-input) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.ant-input:focus) {
  border-color: #104bb8;
  box-shadow: 0 0 0 2px rgba(248, 245, 245, 0.92);
}

/* 分页样式 */
:deep(.ant-pagination) {
  margin-top: 24px;
  text-align: right;
}

:deep(.ant-pagination-prev .ant-pagination-item-link),
:deep(.ant-pagination-next .ant-pagination-item-link),
:deep(.ant-pagination-item) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.ant-pagination-item:hover),
:deep(.ant-pagination-prev:hover .ant-pagination-item-link),
:deep(.ant-pagination-next:hover .ant-pagination-item-link) {
  border-color: #001da1;
  color: #0964ec;
}

:deep(.ant-pagination-item-active) {
  border-color: #0f55d6;
}

:deep(.ant-pagination-item-active a) {
  color: #133a80;
}

/* 标签样式 */
:deep(.ant-tag) {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

:deep(.ant-tag-green) {
  background-color: #f6ffed;
  border-color: #5484e4;
  color: #001da1;
}

:deep(.ant-tag-blue) {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

/* 编辑表单样式 */
.edit-form {
  margin-top: 16px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #333;
}

/* 模态框样式 */
:deep(.ant-modal) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.ant-modal-header) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

:deep(.ant-modal-title) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

:deep(.ant-modal-footer) {
  border-top: 1px solid #e8e8e8;
  padding: 16px 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  #userManagePage {
    padding: 16px;
  }

  .search-card {
    margin-bottom: 16px;
  }

  :deep(.ant-form-inline) {
    flex-direction: column;
    align-items: stretch;
  }

  :deep(.ant-form-item) {
    margin-bottom: 16px;
  }
}
</style>
